import re
devinfo = {}
# 创建空字典
class cisco():
    def __init__(self,*args):
        pass
        #list,带入到cisco中后，自动调用catalyst/ios/nexus等等，通过带入的list不同属性调用不同的func，
        #例如：[filename,catalyst],
        # self.platform = list[2]
        # self.filename = list[1]
        # self......
    def catalyst(filename):
        #将该方法封装为闭包，调用函数catalyst并赋予文件名即可分析出设备信息
        f = open(filename)
        #打开设备show tech 文件
        devinfo['filename'] = filename
        while True:
            #循环读取设备文件每一行
            fdev = f.readline()
            #读取到的行转为名字定义
            uptimeinfo = re.search('Cisco\d+ uptime is （(\d+ years, \d+ month, \d+ weeks, \d+ days, \d+ hours, \d+ minutes)|(\d+ month, \d+ weeks, \d+ days, \d+ hours, \d+ minutes)|(\d+ weeks, \d+ days, \d+ hours, \d+ minutes)|(\d+ days, \d+ hours, \d+ minutes)|(\d+ weeks, \d+ hours, \d+ minutes)|(\d+ hours, \d+ minutes)|(\d+ minutes)）',fdev)
            #匹配uptime时间信息
            if uptimeinfo:
            #如果匹配
                devinfo['uptime'] =uptimeinfo.group()
                #写入devinfo 字典里
            #if uptimeinfo:     
            bootinfo = re.search('System image file is "bootflash:/?.*.bin"',fdev)
            #匹配引导软件版本号
            if bootinfo:
                #如果匹配
                bootver = re.search('cat?.*.bin',bootinfo.group())
                #提取引导版本号
                devinfo['bootimg'] = bootver.group()
                #写入空字典里
            Cio = re.search('CPU utilization for five seconds: (\d)+%/0%; one minute: (\d+)%; five minutes: (\d+)%',fdev)
            #匹配字符串中的文本，读取出设备行
            if Cio:
                #如果匹配到打印出来
                cpio = re.search('\d+',Cio.group())  
                #将匹配到的cpu信息百分比转换为数字转存到字典里
                devinfo['cpuio'] = cpio.group()
                #将匹配到的值，写入空字典中
            meminfo = re.search('Processor Pool Total:  (\d+) Used:  (\d+) Free:   (\d+)',fdev)
            if meminfo:
                total = meminfo.group(1)
                used = meminfo.group(2)
                mem_percent = (((int(used))/(int(total)))*100)
                devinfo['mem_total'] = total
                devinfo['mem_used'] = used
                devinfo['mem_percent'] = mem_percent + '%'
                #ret = re.findall('\d+',meminfo)
                #print(ret)    
            if len(fdev)  == 0:break
            #结束循环
        f.close()
        #关闭文件 
        print (devinfo)
    def ios(filename):
        pass
    def nxos(filename):
        pass
    def nexus(filename):
        pass
    def asa(filename):
        pass
    def firepower(filename):
        pass
    def wlc(filename):
        pass

dev1 = cisco
dev1.catalyst('4948.log')